package com.cz.ssyx.order.task;

import com.cz.ssyx.client.product.ProductFeignClient;
import com.cz.ssyx.common.constant.RedisConst;
import com.cz.ssyx.order.mapper.OrderInfoMapper;
import com.cz.ssyx.vo.order.TimeoutOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/9/10 16:32
 * @version: 1.0
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 */1 * * * ? ")
    public void processTimeoutOrder() {
        //查询出过期未支付的订单  订单号+商品id+数量
        List<TimeoutOrderVo> orderInfoList = orderInfoMapper.selectTimeoutOrder();

        //如果没有超时订单，直接返回
        if (CollectionUtils.isEmpty(orderInfoList)) {
            return;
        }
        List<RLock> rLocks = new ArrayList<>();
        //锁定所有过期的订单id
        orderInfoList.forEach(item ->
                rLocks.add(redissonClient.getFairLock(RedisConst.TIMEOUT_ORDER+ item.getOrderId())));
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(rLocks.toArray(new RLock[0]));
        redissonMultiLock.lock();
        try {
            HashMap<Long, Integer> timeoutOrderMap = new HashMap<>();
            for(TimeoutOrderVo timeoutOrderVo : orderInfoList) {
                Long skuId = timeoutOrderVo.getSkuId();
                Integer skuNum = timeoutOrderVo.getSkuNum();
                timeoutOrderMap.put(skuId, timeoutOrderMap.getOrDefault(skuId, 0) + skuNum);
            }

            // 解锁库存
            productFeignClient.timeOutUnLockStock(timeoutOrderMap);
            //修改订单状态
             orderInfoMapper.processTimeoutOrder();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            redissonMultiLock.unlock();
        }

        //TODO 还要删除订单详细表
    }

}
